package com.example.capsule_netty.controller;

import com.example.capsule_netty.bean.MessageBean;
import com.example.capsule_netty.bean.UserInfoBean;
import com.example.capsule_netty.service.UserInfoService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Base64;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/5 21:26
 */
@RestController
public class UserController {

    @Autowired
    UserInfoService userInfoService;


    @GetMapping("/getUserInfo/{userId}")
    public String getUserInfo(@PathVariable String userId) {
        return userInfoService.getUserInfoByUserId(userId);
    }

    @PostMapping("/updateUserInfo")
    public String updateUserInfo(@RequestBody String user) {
        UserInfoBean userInfoBean = new Gson().fromJson(user, UserInfoBean.class);
        return userInfoService.updateUserInfo(userInfoBean);
    }

    @PostMapping("/uploadAvatar")
    public String uploadAvatar(@RequestBody MessageBean messageBean) {
        return userInfoService.uploadAvatar(messageBean);
    }

    @PostMapping("/getAvatar")
    public String getAvatar(@RequestBody MessageBean messageBean) {
        if (messageBean == null || messageBean.getFilePath() == null) {
            return new Gson().toJson(new MessageBean());
        }
        byte[] data = null;
        try {
            FileInputStream inputStream = new FileInputStream(messageBean.getFilePath());
            data = new byte[inputStream.available()];
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            bufferedInputStream.read(data);
            bufferedInputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] encode;
        encode = Base64.getEncoder().encode(data);
        String bytes = new String(encode);
        int length = bytes.length();
        if (length > 500000) {
            return new Gson().toJson(new MessageBean());
        }
        messageBean = new MessageBean();
        messageBean.setContent(bytes);
        return new Gson().toJson(messageBean);
    }

    @GetMapping("getFriend/{userId}")
    public String getFriend(@PathVariable String userId) {
        return userInfoService.doGetFriends(userId);
    }


    @PostMapping("addFriend")
    public String addFriend(@RequestBody MessageBean messageBean) {
        return userInfoService.doAddFriend(messageBean);
    }

    @GetMapping("getFriendFunctionList/{userId}")
    public String getFriendFunctionList(@PathVariable String userId) {
        return userInfoService.getFriendFunctionList(userId);
    }

    @PostMapping("dealFriendApply")
    public String dealFriendApply(@RequestBody MessageBean messageBean){
        return userInfoService.dealFriendApply(messageBean);
    }


}